package com.jin10.service.impl;

import cn.hutool.core.util.StrUtil;
import com.jin10.annotation.TitleType;
import com.jin10.bean.EconomicsResponse;
import com.jin10.constant.Global;
import com.jin10.constant.TitleIndicatorId;
import com.jin10.dto.BaseArrangeDto;
import com.jin10.dto.NonFarmArrangeDto;
import com.jin10.dto.ParagraphDto;
import com.jin10.entity.BaseInfo;
import com.jin10.service.IBaseInfoService;
import com.jin10.service.ISentenceLibraryService;
import com.jin10.service.ITitleHandlerService;
import com.jin10.util.KeyWordReplace;
import com.jin10.util.Paragraph;
import com.jin10.vo.NonFarmArticleArrangeVo;
import com.jin10.vo.TagTreeVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author raofy
 * @date 2022-02-09 17:24
 * @desc 美国非农就业人口数据公布处理
 */
@Service
@TitleType(value = TitleIndicatorId.US_NON_FARM_PAYROLLS)
public class USNonFarmPayrollsHandler implements ITitleHandlerService {

    private final static String HIGHER_THAN_EXPECTED = "就业人数：%s年%s美国非农新增就业人数为%s万人，高于市场预期的%s万人；%s";
    private final static String LOWER_THAN_EXPECTED = "就业人数：%s年%s美国非农新增就业人数为%s万人，低于市场预期的%s万人； %s";
    private final static String BASICALLY_IN_LINE_EXPECTED = "就业人数：%s年%s美国非农新增就业人数为%s万人，基本符合市场预期的%s万人；%s";
    private final static String GE_PAI = "鸽派结论: %s \n";
    private final static String JIU_JIE = "纠结结论: %s \n";
    private final static String YING_PAI = "鹰派结论: %s \n";

    private final static String HUNGJIN_LIDUO = "黄金利多: %s \n";
    private final static String HUNGJIN_LIKONG = "黄金利空: %s \n";
    private final static String HUNGJIN_ZHENDANG = "黄金震荡: %s \n";

    private final static String BAIYIN_LIDUO = "白银利多: %s \n";
    private final static String BAIYIN_LIKONG = "白银利空: %s \n";
    private final static String BAIYIN_ZHENDANG = "白银震荡: %s \n";

    private final static String MEIYUAN_LIDUO = "美元利多: %s \n";
    private final static String MEIYUAN_LIKONG = "美元利空: %s \n";
    private final static String MEIYUAN_ZHENDANG = "美元震荡: %s \n";

    private final static String MEIGU_LIDUO = "美股利多: %s \n";
    private final static String MEIGU_LIKONG = "美股利空: %s \n";
    private final static String MEIGU_ZHENDANG = "美股震荡: %s \n";

    private final static String MEIZHAI_LIDUO = "美债利多: %s \n";
    private final static String MEIZHAI_LIKONG = "美债利空: %s \n";
    private final static String MEIZHAI_ZHENDANG = "美债震荡: %s \n";

    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    ISentenceLibraryService iSentenceLibraryService;

    @Autowired
    IBaseInfoService iBaseInfoService;

    @Override
    public Object doAction(EconomicsResponse economicsResponse, int year, String month, String day, BaseArrangeDto dto) {
        NonFarmArticleArrangeVo nonFarmArticleArrangeVo = new NonFarmArticleArrangeVo();
        StringBuffer stringBuffer = new StringBuffer();
        if (Objects.isNull(economicsResponse.getConsensus())) {
            economicsResponse.setConsensus(economicsResponse.getPrevious());
        }
        nonFarmArticleArrangeVo.setTitle(String.format("%s-%s非农数据：前值%s，预期%s，公布值%s",Integer.valueOf(month) == 1 ? year - 1 : year, economicsResponse.getTimePeriod(), economicsResponse.getPrevious(), economicsResponse.getConsensus(), economicsResponse.getActual() ));
        stringBuffer.append(getNonFarm(economicsResponse,year, month, day));
        if (dto instanceof NonFarmArrangeDto) {
            // 美联储立场
            if (((NonFarmArrangeDto) dto).getCategories().equals(Global.AUTO)) {
                // 美联储立场（自动）
                fedPositionAuto(Float.valueOf(economicsResponse.getConsensus().toString()), Float.valueOf(economicsResponse.getActual().toString()), stringBuffer, nonFarmArticleArrangeVo);
            } else if (((NonFarmArrangeDto) dto).getCategories().equals(Global.PIGEON)) {
                // 美联储立场（偏鸽）
                stringBuffer.append(getPianGe());
                nonFarmArticleArrangeVo.setCategories(Global.PIGEON);
            } else if (((NonFarmArrangeDto) dto).getCategories().equals(Global.EAGLE)) {
                // 美联储立场（偏鹰）
                stringBuffer.append(getPianYing());
                nonFarmArticleArrangeVo.setCategories(Global.EAGLE);
            } else if (((NonFarmArrangeDto) dto).getCategories().equals(Global.NEUTER)){
                // 美联储立场（中性）
                stringBuffer.append(getJiuJie());
                nonFarmArticleArrangeVo.setCategories(Global.NEUTER);
            }

            // 金银影响
            if (((NonFarmArrangeDto) dto).getType().equals(Global.AUTO)) {
                // 金银（自动）
                goldAndSliver(Float.valueOf(economicsResponse.getConsensus().toString()), Float.valueOf(economicsResponse.getActual().toString()), stringBuffer, nonFarmArticleArrangeVo);
            } else if (((NonFarmArrangeDto) dto).getType().equals(Global.MANY)) {
                // 金银利多
                goldLiDuo(stringBuffer);
                meiYuanKong(stringBuffer);
                nonFarmArticleArrangeVo.setType(Global.MANY);
            } else if (((NonFarmArrangeDto) dto).getType().equals(Global.EMPTY)) {
                // 金银利空
                goldLiKong(stringBuffer);
                meiYuanLiDuo(stringBuffer);
                nonFarmArticleArrangeVo.setType(Global.EMPTY);
            } else if (((NonFarmArrangeDto) dto).getType().equals(Global.NEUTER)){
                // 金银中性
                goldZhenDang(stringBuffer);
                meiYuanDang(stringBuffer);
                nonFarmArticleArrangeVo.setType(Global.NEUTER);
            }
            nonFarmArticleArrangeVo.setData(KeyWordReplace.returnValue(stringBuffer.toString()));
            return nonFarmArticleArrangeVo;
        } else {
            return nonFarmArticleArrangeVo;
        }
    }

    @Override
    public String doAction(EconomicsResponse economicsResponse, int year, String month, String day) {
        if (Objects.nonNull(economicsResponse.getActual())) {
            return KeyWordReplace.returnValue(getNonFarm(economicsResponse, year, month, day));
        } else {
            log.info("非农数据：{}{}{}还没公布，公布时间{}", economicsResponse.getCountry(), economicsResponse.getTimePeriod(), economicsResponse.getName(), economicsResponse.getPubTime());
            return "";
        }
    }


    /**
     * 比较非农数据 整合句子
     *
     * @param economicsResponse
     * @return
     */
    public String getNonFarm(EconomicsResponse economicsResponse, int year, String month, String day) {
        StringBuffer stringBuffer = new StringBuffer();
        // 获取当前非农数据的公布值
        Float actual = Float.valueOf(economicsResponse.getActual().toString());
        // 请求接口获取最值
        Float max = new Float(0.0);
        Float min = new Float(0.0);
        // 预期值与公布值比较
        Float consensus = Float.valueOf(economicsResponse.getConsensus().toString());
        ParagraphDto paragraphDto = new ParagraphDto();
        if (actual > consensus) {
            paragraphDto.setTagIds(Arrays.asList(17));
            List<TagTreeVo> sentenceLibraryByTag = (List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto);
            List<String> strings = Paragraph.returnValue(sentenceLibraryByTag, new StringBuffer());
            stringBuffer.append(String.format(HIGHER_THAN_EXPECTED, Integer.valueOf(month) == 1 ? year - 1 : year, economicsResponse.getTimePeriod(), actual, consensus, strings.get(0)));
//            stringBuffer.append(String.format(HIGHER_THAN_EXPECTED, Integer.valueOf(month) == 1 ? year - 1 : year, economicsResponse.getTimePeriod(), actual, consensus));
        } else if (actual < consensus) {
            paragraphDto.setTagIds(Arrays.asList(19));
            List<TagTreeVo> sentenceLibraryByTag = (List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto);
            List<String> strings = Paragraph.returnValue(sentenceLibraryByTag, new StringBuffer());
            stringBuffer.append(String.format(LOWER_THAN_EXPECTED, Integer.valueOf(month) == 1 ? year - 1 : year, economicsResponse.getTimePeriod(), actual, consensus, strings.get(0)));
//            stringBuffer.append(String.format(LOWER_THAN_EXPECTED, Integer.valueOf(month) == 1 ? year - 1 : year, economicsResponse.getTimePeriod(), actual, consensus));
        } else {
            paragraphDto.setTagIds(Arrays.asList(18));
            List<TagTreeVo> sentenceLibraryByTag = (List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto);
            List<String> strings = Paragraph.returnValue(sentenceLibraryByTag, new StringBuffer());
            stringBuffer.append(String.format(BASICALLY_IN_LINE_EXPECTED, Integer.valueOf(month) == 1 ? year - 1 : year, economicsResponse.getTimePeriod(), actual, consensus, strings.get(0)));
//            stringBuffer.append(String.format(BASICALLY_IN_LINE_EXPECTED, Integer.valueOf(month) == 1 ? year - 1 : year, economicsResponse.getTimePeriod(), actual, consensus));
        }

//        return String.format("%s\n%s\n", KeyWordReplace.returnValue(stringBuffer.toString()), getAssetAnalysis());
        return String.format("%s\n", KeyWordReplace.returnValue(stringBuffer.toString()));
    }

    /**
     * 获取资产分析段落
     *
     * @return
     */
    public String getAssetAnalysis() {
        StringBuffer stringBuffer = new StringBuffer();
        ParagraphDto paragraphDto = new ParagraphDto();

        // 获取偏鸽子数据
//        paragraphDto.setTagIds(Arrays.asList(38));
//        List<String> piange = Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer());
//        stringBuffer.append(String.format(GE_PAI, iSentenceLibraryService.getSentenceById(38) + "；" + iSentenceLibraryService.getSentenceById(47) + "。"));

        // 获取纠结数据
//        paragraphDto.setTagIds(Arrays.asList(39));
//        List<String> jiujie = Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer());
//        if (!jiujie.isEmpty()) {
//            stringBuffer.append(String.format(JIU_JIE, jiujie.get(0)));
//        }
        // 获取偏鹰数据
//        paragraphDto.setTagIds(Arrays.asList(40));
//        List<String> pianying = Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer());
//        stringBuffer.append(String.format(YING_PAI, iSentenceLibraryService.getSentenceById(40) + "；" + iSentenceLibraryService.getSentenceById(57) + "。"));


//        if (!piange.isEmpty()) {
//            stringBuffer.append(String.format(GE_PAI, piange.get(0)));
//        }
//        if (!pianying.isEmpty()) {
//            stringBuffer.append(String.format(YING_PAI, pianying.get(0)));
//        }

        // 添加资产分析（黄金，白银，美元，美股，美债多空结论）
        // 获取黄金利多结论
        paragraphDto.setTagIds(Arrays.asList(42));
        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), HUNGJIN_LIDUO, stringBuffer);

        // 获取黄金利空结论
        paragraphDto.setTagIds(Arrays.asList(41));
        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), HUNGJIN_LIKONG, stringBuffer);

        // 获取黄金震荡结论
        paragraphDto.setTagIds(Arrays.asList(66));
        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), HUNGJIN_ZHENDANG, stringBuffer);

        // 获取白银利多结论
//        paragraphDto.setTagIds(Arrays.asList(67));
//        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), BAIYIN_LIDUO, stringBuffer);

        // 获取白银利空结论
//        paragraphDto.setTagIds(Arrays.asList(68));
//        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), BAIYIN_LIKONG, stringBuffer);

        // 获取美元利多结论
        paragraphDto.setTagIds(Arrays.asList(70));
        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), MEIYUAN_LIDUO, stringBuffer);

        // 获取美元利空结论
        paragraphDto.setTagIds(Arrays.asList(71));
        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), MEIYUAN_LIKONG, stringBuffer);

        // 获取美元震荡结论
        paragraphDto.setTagIds(Arrays.asList(72));
        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), MEIYUAN_ZHENDANG, stringBuffer);

        // 获取美股利多结论
//        paragraphDto.setTagIds(Arrays.asList(46));
//        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), MEIGU_LIDUO, stringBuffer);

        // 获取美股利空结论
//        paragraphDto.setTagIds(Arrays.asList(45));
//        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), MEIGU_LIKONG, stringBuffer);

        // 获取美股震荡结论
//        paragraphDto.setTagIds(Arrays.asList(73));
//        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), MEIGU_LIKONG, stringBuffer);

        // 获取美债利多结论
//        paragraphDto.setTagIds(Arrays.asList(44));
//        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), MEIZHAI_LIDUO, stringBuffer);

        // 获取美债利空结论
//        paragraphDto.setTagIds(Arrays.asList(43));
//        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), MEIZHAI_LIKONG, stringBuffer);

        // 获取美债震荡结论
//        paragraphDto.setTagIds(Arrays.asList(74));
//        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), MEIZHAI_ZHENDANG, stringBuffer);

        return stringBuffer.toString();
    }

    public void getConclusion(List<String> title, String format, StringBuffer buffer) {
        if (!title.isEmpty()) {
            if (!title.get(0).equals("")) {
                buffer.append(String.format(format, title.get(0)));
            }
        }
    }


    /**
     * 美联储立场机器判断
     *
     * @param consensus
     * @param actual
     */
    public void fedPositionAuto(Float consensus, Float actual, StringBuffer stringBuffer, NonFarmArticleArrangeVo nonFarmArticleArrangeVo) {
        // 获取非农标准差
        BaseInfo info = iBaseInfoService.getById(1);
        Float xiaoFuCha = 0f;
        Float xiaoFuHao = 0f;
        Float zhongXingDianLeft = 0f;
        Float zhongXingDianRight = 0f;
        zhongXingDianLeft = consensus - (info.getStandardDev() * info.getMeetExpectation());
        zhongXingDianRight = consensus + (info.getStandardDev() * info.getMeetExpectation());
        xiaoFuHao = consensus + (info.getStandardDev() * info.getSmallGood());
        xiaoFuCha = consensus - (info.getStandardDev() * info.getSmallGood());
        if(actual >= zhongXingDianLeft && actual <= zhongXingDianRight) {
            // 纠结
            stringBuffer.append(getJiuJie());
            nonFarmArticleArrangeVo.setCategories(Global.NEUTER);
        } else if (actual > zhongXingDianRight) {
            // 偏鹰
            stringBuffer.append(getPianYing());
            nonFarmArticleArrangeVo.setCategories(Global.EAGLE);
        } else if (actual < zhongXingDianLeft) {
            // 偏鸽
            stringBuffer.append(getPianGe());
            nonFarmArticleArrangeVo.setCategories(Global.PIGEON);
        }
    }

    /**
     * 获取鸽派结论
     *
     * @return
     */
    public String getPianGe() {
        return String.format(GE_PAI, iSentenceLibraryService.getSentenceById(38) + "；" + iSentenceLibraryService.getSentenceById(47) + "。");
    }

    /**
     * 获取纠结结论
     *
     * @return
     */
    public String getJiuJie() {
        return String.format(JIU_JIE, iSentenceLibraryService.getSentenceById(39) + "；" + iSentenceLibraryService.getSentenceById(57) + "。");
    }

    /**
     * 获取鹰派结论
     *
     * @return
     */
    public String getPianYing() {
        return String.format(YING_PAI, iSentenceLibraryService.getSentenceById(40) + "；" + iSentenceLibraryService.getSentenceById(57) + "。");
    }


    /**
     * 金银机器判断
     *
     * @param consensus
     * @param actual
     */
    public void goldAndSliver(Float consensus, Float actual, StringBuffer stringBuffer, NonFarmArticleArrangeVo nonFarmArticleArrangeVo) {
        // 获取非农标准差
        if(actual > consensus) {
            // 利空
            goldLiKong(stringBuffer);
            meiYuanLiDuo(stringBuffer);
            nonFarmArticleArrangeVo.setType(Global.EMPTY);
        } else if (actual < consensus) {
            // 利多
            goldLiDuo(stringBuffer);
            meiYuanKong(stringBuffer);
            nonFarmArticleArrangeVo.setType(Global.MANY);
        } else {
            // 震荡
            goldZhenDang(stringBuffer);
            meiYuanDang(stringBuffer);
            nonFarmArticleArrangeVo.setType(Global.NEUTER);
        }
    }

    public void goldLiDuo(StringBuffer stringBuffer) {
        ParagraphDto paragraphDto = new ParagraphDto();
        paragraphDto.setTagIds(Arrays.asList(42));
        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), HUNGJIN_LIDUO, stringBuffer);
    }

    public void goldLiKong(StringBuffer stringBuffer) {
        ParagraphDto paragraphDto = new ParagraphDto();
        paragraphDto.setTagIds(Arrays.asList(41));
        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), HUNGJIN_LIKONG, stringBuffer);
    }

    public void goldZhenDang(StringBuffer stringBuffer) {
        ParagraphDto paragraphDto = new ParagraphDto();
        paragraphDto.setTagIds(Arrays.asList(66));
        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), HUNGJIN_ZHENDANG, stringBuffer);
    }


    public void meiYuanLiDuo(StringBuffer stringBuffer) {
        ParagraphDto paragraphDto = new ParagraphDto();
        paragraphDto.setTagIds(Arrays.asList(70));
        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), MEIYUAN_LIDUO, stringBuffer);
    }

    public void meiYuanKong(StringBuffer stringBuffer) {
        ParagraphDto paragraphDto = new ParagraphDto();
        paragraphDto.setTagIds(Arrays.asList(71));
        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), MEIYUAN_LIKONG, stringBuffer);
    }

    public void meiYuanDang(StringBuffer stringBuffer) {
        ParagraphDto paragraphDto = new ParagraphDto();
        paragraphDto.setTagIds(Arrays.asList(72));
        getConclusion(Paragraph.returnValue((List<TagTreeVo>) iSentenceLibraryService.getSentenceByTag(paragraphDto), new StringBuffer()), MEIYUAN_ZHENDANG, stringBuffer);
    }

}
